package com.bestillet.defaultmultishop;

import java.io.IOException;
import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class ShopActivity extends Activity {
	private SwipeRefreshLayout swipe;
	private AlertDialog dialog;
	private Activity context;
	private ListView list;

	private SharedPreferences preferences;
	private ShopApplication app;
	private ShopTask task;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shop);
		
		context = this;
		app = (ShopApplication) getApplicationContext();
		preferences = getSharedPreferences("DefaultShop", MODE_PRIVATE);
		
        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
		swipe.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
        swipe.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				task = new ShopTask();
				task.execute();
			}
		});
        
		list = (ListView) findViewById(android.R.id.list);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				app.setShop(app.getShops().get(position));
				app.clearCategories();
				Intent intent = new Intent(context, CampaignActivity.class);
				startActivity(intent);
			}
		});
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy(); 

		if (task != null)
			if (task.getStatus() == Status.RUNNING)
				task.cancel(true);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		String n = preferences.getString("name", "");
		String p = preferences.getString("phone", "");
		
		if (n.length() <= 0 || p.length() <= 0) {
			Intent customer = new Intent(context, CustomerActivity.class);
			startActivity(customer);
		} else {
			swipe.setRefreshing(true);
			task = new ShopTask();
			task.execute();
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if (dialog != null)
			if (dialog.isShowing())
				dialog.dismiss();
	}
	
	private class ShopTask extends AsyncTask<Integer, Void, Boolean> {
    	@Override
		protected Boolean doInBackground(Integer... params) {
			InputStream in;
			try {
				in = Server.post(Server.SHOPS, Server.getAuthenticationShops(app.getKundeId()));
				XmlPullParser parser = Server.toXmlParser(in);
				app.clearShops();
				app.addShops(XmlParser.getShops(parser));
			} catch (IOException e) {
				Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (XmlPullParserException e) {
				Log.e("Shop", "XmlPullParserException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
				return false;
			} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
			return true;
    	}
    	
	    @Override
	    protected void onPostExecute(Boolean success) {
			swipe.setRefreshing(false);
	    	if (success) {
				ShopArrayAdapter adapter = new ShopArrayAdapter(context, app.getShops());
				list.setAdapter(adapter);
				
				if (app.getShops().size() > 0) {
					// Check if this version is up to date
    				try {
    					Shop shop = app.getShops().get(0);
    					PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
    	    			if (info.versionCode < shop.getVersion()) {
    	    				AlertDialog.Builder builder = new AlertDialog.Builder(context);
    	    	    		builder.setMessage(R.string.dialog_version_message)
    	    	    		       .setTitle(R.string.dialog_version_title)
    	    	    		       .setCancelable(false)
    	    	    		       .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
    	    							@Override
    	    							public void onClick(DialogInterface dialog, int which) {
    	    								try {
    	    									startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getPackageName())));
    	    								} catch (ActivityNotFoundException  e) {
    	    									startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName())));
    	    								}
    	    							}
    	    						});
    	    	    		dialog = builder.create();
    	    	    		dialog.show();
    	    			}
    				} catch (NameNotFoundException e) { }
				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(context);
		    		builder.setMessage(R.string.error_no_shops)
		    		       .setTitle(R.string.error)
		    		       .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) { }
							});
		    		AlertDialog dialog = builder.create();
		    		dialog.show();
				}
	    	} else {
	    		AlertDialog.Builder builder = new AlertDialog.Builder(context);
	    		builder.setMessage(R.string.error_shops)
	    		       .setTitle(R.string.error)
	    		       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								swipe.setRefreshing(true);
								task = new ShopTask();
								task.execute();
							}
						})
						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
	    	}
	    }
	}
}